#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netinet/in.h>

#define N 32

void talk_to_client(int sockfd) {
    int len;
    char buffer[N];

    while (1) {
        len = read(sockfd, buffer, N);
        if (len > 0) {
            write(sockfd, buffer, len);
        }
        else {
            printf("client %d exit.\n", sockfd);
            close(sockfd);
            return;
        }
    }
}

int main(){
    int serv_sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    struct sockaddr_in serv_addr;
    char buffer[N];
    int len;

    memset(&serv_addr, 0, sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
    serv_addr.sin_port = htons(54321);

    bind(serv_sock, (struct sockaddr*)&serv_addr, sizeof(serv_addr));

    listen(serv_sock, 20);
    struct sockaddr_in clnt_addr;
    socklen_t clnt_addr_size = sizeof(clnt_addr);
    printf("server is listening...\n");
    while (1) {
        int clnt_sock = accept(serv_sock, (struct sockaddr*)&clnt_addr, &clnt_addr_size);

        if (!fork()) {
            talk_to_client(clnt_sock);
            exit(0);
        }
    }

    close(serv_sock);
    return 0;
}

